package cn.iqianye.app.qmc

import android.media.MediaPlayer
import java.io.IOException

class ManagedMediaPlayer : MediaPlayer(), MediaPlayer.OnCompletionListener {
    enum class Status {
        IDLE, INITIALIZED, STARTED, PAUSED, STOPPED, COMPLETED
    }

    var state: Status
    private var mOnCompletionListener: OnCompletionListener? = null
    override fun reset() {
        super.reset()
        state = Status.IDLE
    }

    @Throws(IOException::class, IllegalArgumentException::class, SecurityException::class, IllegalStateException::class)
    override fun setDataSource(path: String?) {
        super.setDataSource(path)
        state = Status.INITIALIZED
    }

    override fun start() {
        super.start()
        state = Status.STARTED
    }

    override fun setOnCompletionListener(listener: OnCompletionListener?) {
        mOnCompletionListener = listener
    }

    override fun onCompletion(mp: MediaPlayer?) {
        state = Status.COMPLETED
        if (mOnCompletionListener != null) {
            mOnCompletionListener?.onCompletion(mp)
        }
    }

    @Throws(IllegalStateException::class)
    override fun stop() {
        super.stop()
        state = Status.STOPPED
    }

    @Throws(IllegalStateException::class)
    override fun pause() {
        super.pause()
        state = Status.PAUSED
    }

    val isComplete: Boolean
        get() = state == Status.COMPLETED

    init {
        state = Status.IDLE
        super.setOnCompletionListener(this)
    }
}
